//https://leetcode.cn/problems/spiral-matrix-ii/
package codeRandomThoughts.Test59螺旋矩阵II;

//据说是最好的写法?
public class Solution3 {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        //方向向量,初始向右
        int dx = 0;
        int dy = 1;

        //坐标
        int x = 0;
        int y = 0;

        for (int i = 1; i <= n * n; i++) {
            res[x][y] = i;
            //这个判断语句最巧妙
            //如果撞头就向右调转90度 先加n再对n取模这个操作能防止越界,省了很多判断语句
            if (res[(x + dx + n) % n][(y + dy + n) % n] != 0) {
                int tem = dy;
                dy = -dx;
                dx = tem;
            }
            x += dx;
            y += dy;
        }
        return res;
    }
}